<template>
  <div class="common-layout">
    <!-- 添加学生信息 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="450px"
      append-to-body
      class="dialog"
      @close="closeDialog"
    >
      <el-tabs
        v-model="activeName"
        tab-position="top"
        class="profile-tabs"
        style="margin-top: -15px"
        :stretch="true"
      >
        <el-tab-pane
          :label="$t('students.LinkEinladung')"
          name="link"
          class="profile-tabs-pane"
        >
          <!-- 链接邀请面板 -->
          <el-divider class="enter-x">{{
            $t("students.Einladungslink")
          }}</el-divider>
          <el-form
            ref="linkRef"
            label-position="left"
            style="margin-top: 10px"
            :model="GetLinkeData"
            :rules="rulesfrom"
          >
            <!-- 链接 -->
            <el-form-item>
              <el-input v-model="link" disabled />
              <div style="opacity: 0.6; font-size: 8px">
                {{ $t("students.EinladungslinkLäuft" + GetLinkeData.effectiveTime) }}
              </div>
            </el-form-item>
            <!-- 有效时间 -->
            <el-form-item
              :label="$t('students.WirksameZeit') + '：'"
              prop="effectiveTime"
            >
              <el-select v-model="GetLinkeData.effectiveTime">
                <el-option
                  v-for="dict in course_effective_time"
                  :key="dict.value"
                  :label="
                    translateTagDictI18n('course_effective_time', dict.label)
                  "
                  :value="Number(dict.value)"
                />
              </el-select>
            </el-form-item>
            <!--选择班级 -->
            <el-form-item
              :label="$t('students.KlasseAuswählen') + '：'"
              prop="classId"
            >
              <el-select v-model="GetLinkeData.classId">
                <el-option
                  v-for="item in classList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-button v-throttle="submitLink" class="elbtn" type="primary">{{
              $t("students.LinkGenerieren")
            }}</el-button>
            <el-button v-copy="link" class="elbtn" type="primary">{{
              $t("students.Linkkopieren")
            }}</el-button>
          </el-form>
        </el-tab-pane>
        <!--  直接添加面板 -->
        <el-tab-pane :label="$t('students.DirektHinzufügen')" name="add">
          <el-divider class="enter-x">{{
            $t("students.StudentenEinladen")
          }}</el-divider>
          <el-form
            ref="AddRefFrom"
            :model="AddData"
            :rules="Addrules"
            label-position="left"
            style="margin-top: 10px"
          >
            <el-form-item
              :label="$t('students.MethodeHinzufügen') + '：'"
              prop="flag"
            >
              <el-radio-group v-model="AddData.flag">
                <el-radio :label="0">{{
                  $t("students.Mobiltelefonnummer")
                }}</el-radio>
                <el-radio :label="1">{{
                  $t("students.Studentenausweis")
                }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              :label="$t('students.KlasseAuswählen') + '：'"
              prop="classId"
            >
              <el-select v-model="AddData.classId" style="width: 100%">
                <el-option
                  v-for="item in classList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              :label="
                AddData.flag === 0
                  ? $t('students.BitteTelefonnummer') + '：'
                  : $t('students.Studentenausweis') + '：'
              "
              prop="keywords"
              style="width: 100%"
            >
              <el-input
                v-model="AddData.keywords"
                :placeholder="
                  AddData.flag === 0
                    ? $t('students.BitteTelefonnummer')
                    : $t('students.BitteStudierendenausweis')
                "
              />
            </el-form-item>
            <el-button v-throttle="AddStudentInfo" type="primary">{{
              $t("students.Hinzufügenbestätigen")
            }}</el-button>
          </el-form>
        </el-tab-pane>
        <!-- 二维码添加面板 -->
        <el-tab-pane :label="$t('students.EinladungQRCode')" name="qrcode">
          <el-divider class="enter-x">{{
            $t("students.QRCodeAnzumelden")
          }}</el-divider>
          <el-row style="maring-left: -10px; maring-right: -10px">
            <el-col :span="24" style="padding-left: 10px; padding-right: 10px">
              <el-card class="mb-10px text-center" shadow="hover">
                <svg-icon
                  icon-class="daiwanshan"
                  style="width: 50%; height: 50%"
                />
              </el-card>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <el-card shadow="never" style="margin: 20px">
      <el-container>
        <el-header>
          <!-- 搜索学生、添加学生展板 -->
          <div class="search-container">
            <el-form :inline="true">
              <el-form-item>
                <el-input
                  v-model="StudentData.keywords"
                  :placeholder="$t('students.SucheNachStudenten')"
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
              <el-form-item>
                <el-button v-throttle="handleQuery" type="primary"
                  ><el-icon style="margin-right: 5px; font-size: 18px">
                    <Search /> </el-icon
                  >{{ $t("students.Suche") }}</el-button
                >
              </el-form-item>
              <el-form-item>
                <el-button v-throttle="resetting" type=""
                  ><el-icon style="margin-right: 5px; font-size: 18px">
                    <Refresh /> </el-icon
                  >{{ $t("students.Zurücksetzen") }}</el-button
                >
              </el-form-item>
              <el-button
                v-hasPerm="['courseinfo:students:add']"
                v-throttle="openDialog"
                class="addcourse"
                type=""
                plain
                style="color: var(--el-color-primary)"
                ><svg-icon
                  icon-class="classadd"
                  style="margin-right: 5px; font-size: 24px"
                />{{ $t("students.StudentenEinladen") }}</el-button
              >
            </el-form>
          </div>
        </el-header>
        <el-main>
          <!-- 列表 -->
          <el-card style="margin-top: 15px" shadow="never">
            <template #header>
              <div class="flex justify-between">
                <div>
                  <el-button
                    v-throttle="handleDelete"
                    v-hasPerm="['courseinfo:students:delete']"
                    :disabled="ids.length === 0"
                    type="danger"
                    ><i-ep-delete style="margin-right: 2px" />{{
                      $t("students.löschen")
                    }}</el-button
                  >
                </div>
              </div>
            </template>
            <div class="tableto">
              <el-table
                v-loading="tabloading"
                border
                :data="studentList"
                :empty-text="$t('students.Studenteninformationen')"
                @selection-change="handleSelectionChange"
              >
                <el-table-column
                  fixed
                  type="selection"
                  width="50"
                  align="center"
                />
                <el-table-column
                  key="nickname"
                  :label="$t('students.Name')"
                  align="center"
                  prop="nickname"
                />
                <el-table-column
                  :label="$t('students.Studentenausweis')"
                  prop="codeId"
                  align="center"
                >
                  <template #default="scope">
                    <el-text
                      v-if="scope.row.codeId == null"
                      style="opacity: 0.8; font-size: 12px; margin: 0 auto"
                      >{{ $t("students.DerzeitStudierendenausweis") }}</el-text
                    >
                  </template>
                </el-table-column>
                <el-table-column
                  key="className"
                  :label="$t('students.Klasse')"
                  align="center"
                  prop="className"
                  :show-overflow-tooltip="true"
                  style="
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                  "
                />
                <el-table-column
                  key="deptName"
                  :label="$t('students.Organisation')"
                  align="center"
                  prop="deptName"
                >
                  <template #default="scope">
                    <el-text
                      v-if="scope.row.deptName == null"
                      style="opacity: 0.8; font-size: 12px; margin: 0 auto"
                      >{{ $t("students.Vorübergehendunorganisiert") }}</el-text
                    >
                  </template>
                </el-table-column>
                <el-table-column
                  key="mobile"
                  :label="$t('students.Mobiltelefonnummer')"
                  align="center"
                  prop="mobile"
                />
                <el-table-column
                  key="genderLabel"
                  :label="$t('students.Geschlecht')"
                  align="center"
                  prop="genderLabel"
                >
                  <template #default="scope">
                    <el-tag class="ml-2" :type="status(scope.row.genderLabel)">
                      {{ scope.row.genderLabel }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column
                  key="userId"
                  v-hasPerm="['courseinfo:students:delete']"
                  :label="$t('students.Betrieb')"
                  align="center"
                  prop="userId"
                >
                  <!-- 这里填写操作 -->
                  <template #default="scope">
                    <el-button
                      v-throttle="
                        () =>
                          deletestudentfn(scope.row.userId, scope.row.classId)
                      "
                      type="danger"
                      size="small"
                      link
                      ><el-icon style="margin-right: 2px">
                        <Delete />
                      </el-icon>
                      {{ $t("students.löschen") }}</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
              <!-- 分页 -->
              <pagination
                v-if="total > 0"
                v-model:total="total"
                v-model:page="StudentData.pageNum"
                v-model:limit="StudentData.pageSize"
                @pagination="handleQuery"
              />
            </div>
          </el-card>
        </el-main>
      </el-container>
    </el-card>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Students",
  inheritAttrs: false,
});
// API依赖
import {
  AddLinkStudent,
  DeleteStudent,
  DeleteStudents,
  DirectAddStudent,
  getStudentPage,
  getclasslist,
} from "@/api/student/index";
import {
  StudentPageVO,
  StudentQuery,
  DeleteStudentData,
  AddLinkStudentData,
  AddStudentData,
} from "@/api/student/types";
import { useAppStore } from "@/store/modules/app";
import { translateTagDictI18n } from "@/utils/i18n";
import { FormRules } from "element-plus";
import { useCourseStore } from "@/store/modules/course";

// 字典引入
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { course_effective_time } = proxy?.useDict("course_effective_time"); // 有效时间
const appStore = useAppStore();
// 获取信息type
interface classListType {
  id: number;
  name: string;
}
const courseStore = useCourseStore();
const courseId = ref();
const tabloading = ref(false);
const classList = ref<classListType[]>();
const linkRef = ref(ElForm); // 创建表单
const AddRefFrom = ref(ElForm);
// 请求链接数据
const GetLinkeData = reactive<AddLinkStudentData>({
  // 初始化
  effectiveTime: 3, // 初始化有效时间
});
// 直接添加数据
// 请求链接数据
const AddData = reactive<AddStudentData>({
  flag: 0,
});
// 使用 ref 创建响应式数据
const activeName = ref("link"); // 当前激活的标签页
const link = ref(""); // 邀请链接
// 获取列表数据信息
const ids = ref([]);
const studentList = ref<StudentPageVO[]>(); // 列表总数
const total = ref(0); // total
// 请求学生分页参数
const StudentData = reactive<StudentQuery>({
  pageNum: 1,
  pageSize: 10,
});
// 删除学生请求参数
const DeleteStudentData = reactive<DeleteStudentData>({
  userId: 0, // 学生id
  classId: 0, // 班级id
});
//表单规则
const rulesfrom = ref<FormRules>({
  effectiveTime: [
    { required: true, message: "请选择链接有效时间", trigger: "blur" },
  ],
  classId: [{ required: true, message: "请选择班级", trigger: "blur" }],
});
// 直接添加表单规则
const Addrules = ref<FormRules>({
  flag: [{ required: true, trigger: "blur", message: "请选择添加方式" }],
  classId: [{ required: true, trigger: "blur", message: "请选择班级" }],
  keywords: [{ required: true, trigger: "blur", validator: phoneValidator }],
});

// 封装手机号验证规则
function isvalidPhone(phone: string) {
  const reg = /^1([38][0-9]|4[014-9]|[59][0-35-9]|6[2567]|7[0-8])\d{8}$/;
  return reg.test(phone);
}

// 手机号校验器 phoneValidator
function phoneValidator(_rule: any, value: string, callback: any) {
  if (!value && AddData.flag == 0) {
    callback(new Error("请填写电话号码"));
  } else if (!isvalidPhone(value) && AddData.flag == 0) {
    //判断用户输入的值是否符合规则
    callback(new Error("请填写正确的11位手机号码"));
  } else if (!value && AddData.flag == 1) {
    callback(new Error("请填写学号"));
  } else {
    callback();
  }
}
// 定义一个方法，处理链接邀请的表单提交事件
function submitLink() {
  linkRef.value.validate((valid: boolean) => {
    if (valid) {
      AddLinkStudent(GetLinkeData, courseId.value)
        .then(({ data }) => {
          link.value = data;
          ElMessage.success("链接已生成");
        })
        .catch((err) => {
          console.log("err", err);
        });
    }
  });
}
// 直接添加学生信息
function AddStudentInfo() {
  AddRefFrom.value.validate((valid: boolean) => {
    if (valid) {
      DirectAddStudent(AddData, courseId.value)
        .then(() => {
          ElMessage.success("学生已添加到课程中!");
          handleQuery(); //更新
          closeDialog();
        })
        .catch((err) => {
          console.log(err);
        });
    }
  });
}
// 判断处理状态标签颜色函数
function status(label: string) {
  if (label === "男") {
    return "";
  } else {
    return "success";
  }
}

// 搜索函数
function handleQuery() {
  tabloading.value = true;
  getStudentPage(StudentData, courseId.value)
    .then(({ data }) => {
      studentList.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      tabloading.value = false;
    });
}
// 删除学生函数
function deletestudentfn(userId: number, classId: number) {
  DeleteStudentData.userId = userId;
  DeleteStudentData.classId = classId;

  ElMessageBox.confirm("确认删除学生?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    DeleteStudent(DeleteStudentData, courseId.value)
      .then(({ data }) => {
        ElMessage.success("删除学生成功!");
        handleQuery(); // 重新刷新
      })
      .catch((err) => {
        console.log(err);
      });
  });
}

// 重置函数
function resetting() {
  // 重置信息
  StudentData.keywords = "";
  handleQuery(); // 再搜一遍
}

// 创建弹窗组件
const dialog = reactive<DialogOption>({
  visible: false,
});
// 打开弹窗
function openDialog() {
  dialog.visible = true;
  dialog.title = "邀请加入";
  // 获取班级信息
  getclasslist(courseId.value).then(({ data }) => {
    classList.value = data;
  });
}
// 关闭弹窗
function closeDialog() {
  dialog.visible = false;
  /* 重置链接信息 */
  link.value = "";
}

/**
 * 行checkbox change事件
 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => {
    return {
      userId: item.userId,
      classId: item.classId,
    };
  });
}

/**
 * 删除用户
 */
function handleDelete() {
  const userIds = ids.value;

  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }
  ElMessageBox.confirm("确认删除所勾选的学生?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    DeleteStudents(userIds, courseId.value).then((res) => {
      ElMessage.success("批量删除成功!");
      handleQuery();
    });
  });
}

// 进来就搜
onMounted(() => {
  courseId.value = courseStore.courseId;
  handleQuery();
  // 隐藏展板
  appStore.sidebar.opened = false;
});
</script>

<style lang="scss" scoped>
.search-container {
  margin-top: 15px;
}

.addcourse {
  position: absolute;
  /* 绝对定位，相对于最近的定位祖先元素 */
  right: 80px;
}

.user {
  max-height: 960px;
  padding: 15px 20px 20px;
}

.elbtn {
  color: white;
  font-weight: bolder;
  font-size: 14px;
  margin-top: 10px;
  margin-bottom: 10px;
}
.el-text {
  margin-left: 20px;
  font-weight: bold;
}
</style>
